package cn.mesmile.excel.xml;


import cn.hutool.core.io.FileUtil;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;

/**
 * @author zb
 * @date 2021/11/17 10:25
 * @Description
 */
@Service
public class ReadXmlService {


    public List<LinkedHashMap<String, Object>> readXml(InputStream inputStream) throws DocumentException {
        List<LinkedHashMap<String, Object>> data = new ArrayList<>();
        //1.创建Reader对象
        SAXReader reader = new SAXReader();
        reader.setEncoding("UTF-8");
        //2.加载xml
        Document document = reader.read(inputStream);
        String encoding = reader.getEncoding();
        System.out.println("encoding = " + encoding);
        //3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()) {
            Element stu = (Element) iterator.next();
            List<Attribute> attributes = stu.attributes();
            LinkedHashMap<String, Object> map = new LinkedHashMap<>();
            for (Attribute attribute : attributes) {
                map.put(attribute.getName(),attribute.getValue());
            }
            data.add(map);
        }
        return data;
    }


    /**
     *  dom4j 完整读取 xml 示例
     * @param args
     * @throws Exception
     */
    public  void read(String[] args) throws Exception {
        //1.创建Reader对象
        SAXReader reader = new SAXReader();
        //2.加载xml
        Document document = reader.read(FileUtil.file("D:\\xml\\4.xml"));
        //3.获取根节点
        Element rootElement = document.getRootElement();
        Iterator iterator = rootElement.elementIterator();
        while (iterator.hasNext()) {
            Element stu = (Element) iterator.next();
            List<Attribute> attributes = stu.attributes();
            System.out.println("======获取属性值======");
            for (Attribute attribute : attributes) {
                System.out.println(attribute.getName());
                System.out.println(attribute.getValue());
            }
            System.out.println("======遍历子节点======");
            Iterator iterator1 = stu.elementIterator();
            while (iterator1.hasNext()) {
                Element stuChild = (Element) iterator1.next();
                System.out.println("节点名：" + stuChild.getName() + "---节点值：" + stuChild.getStringValue());
            }
        }
    }
}
